<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-header-actions">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workflow-templates' }">工作流模板管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/workflow-templates/${templateId}/versions` }">
            版本历史
          </el-breadcrumb-item>
          <el-breadcrumb-item>版本详情</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="action-buttons">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <el-card v-loading="loading" class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">版本信息</span>
          <el-tag type="primary">v{{ versionData.version }}</el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="模板名称">{{ versionData.name }}</el-descriptions-item>
        <el-descriptions-item label="版本号">v{{ versionData.version }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ versionData.description || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="变更说明" :span="2">
          {{ versionData.change_log || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="父版本ID">
          {{ versionData.parent_version_id || '无（初始版本）' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建人">
          {{ versionData.created_by || '系统' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(versionData.created_at) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="detail-card">
      <template #header>
        <span class="card-title">工作流定义</span>
      </template>

      <div class="workflow-visualization">
        <WorkflowEditor
          v-model="workflowData"
          :readonly="true"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWorkflowTemplateStore } from '@/stores/workflowTemplate'
import WorkflowEditor from '@/components/WorkflowEditor/index.vue'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const templateStore = useWorkflowTemplateStore()

const templateId = ref(parseInt(route.params.id))
const version = ref(parseInt(route.params.version))
const loading = ref(false)
const versionData = ref({})

const workflowData = computed(() => {
  if (!versionData.value.workflow_definition || !versionData.value.workflow_definition.nodes) {
    return { nodes: [], edges: [] }
  }

  const definition = versionData.value.workflow_definition
  const edges = []
  const nodePositions = new Map()
  const nodeMap = new Map()
  const inDegree = new Map()

  definition.nodes.forEach(node => {
    nodeMap.set(node.id, node)
    inDegree.set(node.id, 0)
  })

  definition.nodes.forEach(node => {
    if (node.next) {
      const nextNodes = Array.isArray(node.next) ? node.next : [node.next]
      nextNodes.forEach(nextId => {
        if (inDegree.has(nextId)) {
          inDegree.set(nextId, inDegree.get(nextId) + 1)
        }

        edges.push({
          id: `edge_${node.id}_${nextId}`,
          type: 'smoothstep',
          source: node.id,
          target: nextId,
          animated: true
        })
      })
    }
  })

  const sortedNodes = []
  const queue = []

  inDegree.forEach((degree, nodeId) => {
    if (degree === 0) {
      queue.push(nodeId)
    }
  })

  while (queue.length > 0) {
    const nodeId = queue.shift()
    sortedNodes.push(nodeId)

    const node = nodeMap.get(nodeId)
    if (node && node.next) {
      const nextNodes = Array.isArray(node.next) ? node.next : [node.next]
      nextNodes.forEach(nextId => {
        if (inDegree.has(nextId)) {
          inDegree.set(nextId, inDegree.get(nextId) - 1)
          if (inDegree.get(nextId) === 0) {
            queue.push(nextId)
          }
        }
      })
    }
  }

  definition.nodes.forEach(node => {
    if (!sortedNodes.includes(node.id)) {
      sortedNodes.push(node.id)
    }
  })

  sortedNodes.forEach((nodeId, index) => {
    nodePositions.set(nodeId, { x: 180 + index * 300, y: 90 })
  })

  const nodes = definition.nodes.map(node => ({
    id: node.id,
    type: node.type === 'condition' ? 'condition_branch' : node.type,
    position: nodePositions.get(node.id) || { x: 0, y: 0 },
    data: {
      label: node.name || node.type,
      config: node.config || {}
    }
  }))

  return { nodes, edges }
})

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : ''
}

const fetchVersionDetail = async () => {
  loading.value = true
  try {
    const data = await templateStore.fetchVersionDetail(templateId.value, version.value)
    versionData.value = data
  } catch (error) {
    console.error('获取版本详情失败:', error)
    ElMessage.error('获取版本详情失败')
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  router.push(`/workflow-templates/${templateId.value}/versions`)
}

onMounted(() => {
  fetchVersionDetail()
})
</script>

<style lang="scss" scoped>
.detail-card {
  margin-bottom: 20px;

  :deep(.el-card__header) {
    padding: 16px 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.page-header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.workflow-visualization {
  height: 500px;

  :deep(.workflow-editor-container) {
    height: 100%;
  }
}
</style>
